using UnityEngine;
using System;
using System.Collections;
using DanielSig.UnityExtensions;
using DanielSig;

public class ArcSensor : MonoBehaviour, ISensor
{
	public bool HasFixedDirection{ get{ return true; } }
	public SensationType Type{ get{ return _type; } }
	public float[] Values{ get{ return _values; } }
	
	[SerializeField]
	private SensationType _type;
	
	[SerializeField]
	private float[] _values = new float[2];
	
	[Range(1,100)]
	public float Range = 50F;
	[Range(1,90)]
	public float Angle = 0F;
	public int Resolution = 6;
	public LayerMask Mask;
	public Color ArcColor = Color.red;
	
	private float[] _distances = new float[1];
	private Quaternion _prevRotation;
	
	public void UpdateSensors ()
	{
		if(Resolution != _distances.Length)
			_distances = new float[Resolution];
		
		float minDist = Range;
		_type = SensationType.None;
		
		float step = Angle / Resolution.Max(1);
		int halfRes = Resolution / 2;
		
		int counter = 0;
		for(int i = -halfRes; i < halfRes; i++)
		{
			Ray laser = new Ray(transform.position, transform.forward.RotateY(step * (i + 0.5F)));
			RaycastHit hit = laser.GetHit(Range, Mask.value);
			if(hit.collider)
			{
				if(hit.distance < minDist)
				{
					_type = hit.collider.Request<SensationType>("Observation", SensationType.None);
					_values[0] = minDist = hit.distance;
				}
				_distances[counter] = hit.distance;
			}
			else
			{
				_distances[counter] = Range;
			}
			counter++;
		}
		_values[1] = transform.localEulerAngles.y / 180F;
		_prevRotation = transform.rotation;
	}
	void OnDrawGizmos()
	{
		float step = Angle / Resolution.Max(1);
		int halfRes = Resolution / 2;
		
		Gizmos.color = ArcColor;
		
		int counter = 0;
		if(Resolution != _distances.Length)
			Array.Resize<float>(ref _distances, Resolution);
		
		for(int i = -halfRes; i < halfRes; i++)
		{
			float dist = _distances[counter++];
			if(dist == 0) dist = Range;
			
			Ray laser = new Ray(transform.position, (_prevRotation * Vector3.forward).RotateY(step * (i + 0.5F)));
			Gizmos.DrawRay(laser.origin, laser.direction * dist);
		}
	}
	void OnDrawGizmosSelected()
	{
		Gizmos.color = ArcColor.SetAlpha(0.15F);
		Gizmos.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0,-45, 0), Vector3.one);
		Gizmos.matrix = Matrix4x4.Scale(new Vector3(Mathf.Sin(Angle * 0.5F * Mathf.Deg2Rad), 1, 1)) * Gizmos.matrix;
		Gizmos.matrix = Matrix4x4.TRS(Vector3.zero, transform.rotation, Vector3.one) * Gizmos.matrix;
		Gizmos.matrix = Matrix4x4.TRS(transform.position, Quaternion.identity, Vector3.one) * Gizmos.matrix;
		Gizmos.DrawCube(new Vector3(1,0,1) * Range * 0.5F, new Vector3(Range, 0.1F, Range));
	}
}

